<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //浅拷贝，这里只是传递了地址
        let tw={name:"唐玮"};
        let new_tw=tw;
        new_tw.name="sb";//也将原来的地址的内容改变了
        console.log(tw);//{name:sb}

        
        //不改变原来的对象
        let new_obj={
            name:tw.name
        };
        new_obj.name="new_obj";
        console.log(tw.name); //sb

        //拷贝直接用Object接口assign
        let new_tw1=Object.assign({age:25},tw);
        console.log(new_tw1);

        //深拷贝
// let user={
//     name:"唐玮",
//     password:{
//         name:123456
//     }
  
// }
// function copy(Object){
//     let copy_obj={};
//     for (const key in Object) {
//         copy_obj[key]=
//          typeof Object[key] == "object" 
//          ?copy(Object[key])
//          :Object[key];//判断；如果是对象的话就再递归遍历一遍，不是就直接传递
                                            
      
//   }
//   return copy_obj;
// }
// let a=copy(user); //
// user.name="sb"
// console.log(a);

// //

//如果里面有对象，又有数组?
let user={
    name:"唐玮",
    password:{
        name:123456
    },
    arr:[]
  
}

function  copy(obj){
    //判断Object为数组还是对象
    let res=obj instanceof   Array ? [] :{};
    for (const [k,v] of Object.entries(obj)) {
          res[k] = typeof v == "object" ? copy(v):v;
    }
    return res;
}

let new_copy_obj=copy(user);
user.arr.push(123);

console.log(JSON.stringify(new_copy_obj,null,2));
console.log(JSON.stringify(user,null,2));


    
    </script>
</body>
</html>